
#include <new>

#include "Graphics/Manager.hpp"

using namespace	Graphics;

Manager::Manager() :
	AManager(),
	_window(new(std::nothrow) sf::RenderWindow),
	_color(0, 0, 0),
	_configuration()
{
	this->_initialize();
}

Manager::Manager(Configuration const &conf) :
	AManager(),
	_window(new(std::nothrow) sf::RenderWindow),
	_color(0, 0, 0),
	_configuration(conf)
{
	this->_initialize();
}


bool		Manager::create()
{
	if (!this->isOpened() && this->_isValidConfiguration())
	{
		this->_window->Create(sf::VideoMode(this->_configuration.getWidth(), this->_configuration.getHeight(),
											this->_configuration.getColor()),
							  this->_configuration.getTitle(), this->_configuration.getWindowed() ? sf::Style::Close : sf::Style::Fullscreen);
		this->_window->UseVerticalSync(this->_configuration.getVSync());
		this->_window->SetFramerateLimit(this->_configuration.getFrameRate());

		return true;
	}

	return false;
}

bool		Manager::recreate()
{
	if (this->isOpened())
		this->_window->Close();

	return this->create();
}

bool		Manager::close()
{
	if (!this->isOpened())
		return false;

	this->_window->Close();
	return true;
}


void		Manager::setConfiguration(Configuration const &conf)
{
	this->_configuration = conf;
}

void		Manager::setColor(char unsigned r, char unsigned g, char unsigned b)
{
	this->_color.r = r;
	this->_color.g = g;
	this->_color.b = b;
}


bool		Manager::isValid() throw()
{
	return (this->_isValid && this->_isValidConfiguration());
}

bool		Manager::isOpened() throw()
{
	return (this->_window->IsOpened());
}


void		Manager::display()
{
	this->_window->Display();

	sf::Event	event;
	while (this->_window->GetEvent(event))
	{
		if (event.Type == sf::Event::Closed)
			this->_window->Close();
	#ifdef DEBUG
		else if (event.Type == sf::Event::KeyPressed
				 && event.Key.Code == sf::Key::Escape)
			this->_window->Close();
	#endif
	}
}

void		Manager::clear()
{
	this->_window->Clear(this->_color);
}


Manager::~Manager() throw()
{
}


bool		Manager::_initialize()
{
	if (!this->_window)
		return (this->_isValid = false);

	this->_isValid = true;

	return this->isValid();
}

bool			Manager::_isValidConfiguration() throw()
{
	std::size_t	i = 0;
	std::size_t	count = sf::VideoMode::GetModesCount();

	for ( ; i < count ; ++i)
	{
		sf::VideoMode	mode;

		mode = sf::VideoMode::GetMode(i);
		if (this->_configuration.getWidth() == mode.Width
			&& this->_configuration.getHeight() == mode.Height
			&& this->_configuration.getColor() <= mode.BitsPerPixel)
			break ;
	}

	if (i == count)
		return (this->_isValid = false);
	return true;
}
